package org.andromda.android.net;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.CookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;

import android.text.TextUtils;

public class SessionAuthenticationStrategy implements AuthenticationStrategy {

	private final String unauthorizedUrlPattern;

	public SessionAuthenticationStrategy(final String unauthorizedUrlPattern) {
		this.unauthorizedUrlPattern = unauthorizedUrlPattern;
	}

	@Override
	public String authenticationGetParameter(final String url,
			final ConnectionData prefs, final String ticket) {
		return null;
	}

	@Override
	public void checkUnauthorizedResponse(final NetworkUtils nwUtils,
			final HttpResponse response) throws NetworkException {
		final StatusLine statusLine = response.getStatusLine();
		final int statusCode = statusLine.getStatusCode();
		final String reason = statusLine.getReasonPhrase();
		if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY
				|| statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
			final String redirectUrl = NetworkUtils.getRedirectUrl(response);
			if (unauthorizedUrl(redirectUrl)) {
				throw new NetworkException(NetworkStatus.CREDENTIALS_ERROR,
						statusCode, reason);
			}
		}

	}

	@Override
	public void setAuthCookies(final ConnectionData prefs, final String ticket,
			final CookieStore cookieStore) {
		if (ticket != null) {
			final String[] ticketParts = ticket.split("=");
			BasicClientCookie cookie;
			if (ticketParts.length == 2) {
				cookie = new BasicClientCookie(ticketParts[0], ticketParts[1]);
			} else {
				cookie = new BasicClientCookie("JSESSIONID", ticket);
			}
			final String webappRoot = prefs.getWebappRoot();
			cookie.setPath(webappRoot);
			cookie.setDomain(prefs.getHostName());
			cookieStore.addCookie(cookie);
		}
	}

	protected boolean unauthorizedUrl(final String redirectUrl) {
		boolean result = false;
		if (!TextUtils.isEmpty(this.unauthorizedUrlPattern)) {
			result = redirectUrl.matches(this.unauthorizedUrlPattern);
		}
		return result;
	}

}
